#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;
class Ticket
{
public:
    Ticket() :tickets(100)
    {
        pthread_mutex_init(&mtx,nullptr);
    }
    ~Ticket()
    {
        pthread_mutex_destroy(&mtx);
    }
    bool GetTicket()
    {
        bool res = true;
        pthread_mutex_lock(&mtx);
        if(tickets > 0)
        {
            usleep(100);
            cout <<"我是["<<pthread_self()<<"],我抢的票是:"<<tickets<< " "<<endl;
            tickets != 0 ? tickets--:tickets;
        }
        else
        {
            cout << "票被抢光了............"<<endl;
            res = false;
        }
        pthread_mutex_unlock(&mtx);
        return res;
    }

private:
    int tickets;
    pthread_mutex_t mtx;
};
void* ThreadRun(void* args)
{
    Ticket* t = (Ticket*)args;
    while(1)
    {
        if(!t->GetTicket())
        {
            break;
        }
    }
    return nullptr;
}
int main()
{
    Ticket* t = new Ticket();
    pthread_t tids[5];
    for(int i = 0;i<5;i++)
    {
        pthread_create(tids+i,nullptr,ThreadRun,(void*)t);
    }
    for(int i = 0;i<5;i++)
    {
        pthread_join(tids[i],nullptr);
    }
    return 0;
}